import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../providers/app_state.dart';
import '../widgets/theme_selector.dart';
import '../services/api_service.dart';

class ResultPage extends StatefulWidget {
  const ResultPage({super.key});

  @override
  State<ResultPage> createState() => _ResultPageState();
}

class _ResultPageState extends State<ResultPage>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _fadeAnimation;
  late Animation<Offset> _slideAnimation;

  String? _shortLink;
  bool _isGeneratingLink = false;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );
    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeInOut),
    );
    _slideAnimation =
        Tween<Offset>(begin: const Offset(0, 0.3), end: Offset.zero).animate(
          CurvedAnimation(
            parent: _animationController,
            curve: Curves.easeOutCubic,
          ),
        );
    _animationController.forward();
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).colorScheme.background,
      body: SafeArea(
        child: Column(
          children: [
            // 顶部工具栏
            _buildTopBar(),

            // 主内容区域
            Expanded(
              child: Consumer<AppState>(
                builder: (context, appState, child) {
                  if (appState.analysisResult == null) {
                    return const Center(child: CircularProgressIndicator());
                  }

                  return FadeTransition(
                    opacity: _fadeAnimation,
                    child: SlideTransition(
                      position: _slideAnimation,
                      child: SingleChildScrollView(
                        padding: const EdgeInsets.all(16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // 完成祝贺
                            _buildCompletionCard(),

                            const SizedBox(height: 24),

                            // 因子得分图表
                            _buildTotalScoreChart(appState),

                            const SizedBox(height: 24),

                            // 详细分析报告
                            _buildAnalysisReport(appState),

                            const SizedBox(height: 24),

                            // 分享和操作按钮
                            _buildActionButtons(appState),

                            const SizedBox(height: 32),

                            // 免责声明
                            _buildDisclaimer(),

                            const SizedBox(height: 100), // 底部空间
                          ],
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTopBar() {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              IconButton(
                onPressed: () {
                  context.read<AppState>().reset();
                  context.read<AppState>().setCurrentPage(0);
                },
                icon: const Icon(Icons.home),
              ),
              const SizedBox(width: 8),
              Text(
                '测试结果',
                style: Theme.of(context).textTheme.headlineMedium?.copyWith(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
          const ThemeSelector(),
        ],
      ),
    );
  }

  Widget _buildCompletionCard() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            Theme.of(context).primaryColor.withOpacity(0.1),
            Theme.of(context).primaryColor.withOpacity(0.05),
          ],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(
          color: Theme.of(context).primaryColor.withOpacity(0.2),
        ),
      ),
      child: Column(
        children: [
          Container(
            width: 80,
            height: 80,
            decoration: BoxDecoration(
              color: Theme.of(context).primaryColor,
              shape: BoxShape.circle,
            ),
            child: const Icon(Icons.check, color: Colors.white, size: 40),
          ),
          const SizedBox(height: 16),
          Text(
            '测试完成！',
            style: Theme.of(context).textTheme.headlineMedium?.copyWith(
              fontSize: 24,
              fontWeight: FontWeight.bold,
              color: Theme.of(context).primaryColor,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '感谢您完成SCL-90心理健康评估',
            style: Theme.of(
              context,
            ).textTheme.bodyLarge?.copyWith(color: Colors.grey.shade600),
          ),
          const SizedBox(height: 16),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            decoration: BoxDecoration(
              color: Colors.green.shade100,
              borderRadius: BorderRadius.circular(20),
            ),
            child: Text(
              '已完成90题评估',
              style: TextStyle(
                color: Colors.green.shade700,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTotalScoreChart(AppState appState) {
    final totalScores = appState.calculateSCLTotalScore();
    final totalScore = totalScores['总分'] ?? 0.0;
    final averageScore = totalScores['平均分'] ?? 0.0;

    String getScoreLevel(double score) {
      if (score <= 180) return '✅ 正常';
      if (score <= 270) return '⚠️ 轻度困扰';
      if (score <= 360) return '❗️中度困扰';
      if (score <= 405) return '❗️较重困扰';
      return '🚨 严重困扰';
    }

    String getScoreSuggestion(double score) {
      if (score <= 180) return '情绪稳定、心理状态良好，无明显困扰';
      if (score <= 270) return '可能有部分压力或不适，建议适当调节情绪';
      if (score <= 360) return '明显困扰，建议重视心理调节，可考虑咨询';
      if (score <= 405) return '情绪状态较差，日常功能可能受影响，建议咨询专业人士';
      return '情绪压力非常大，强烈建议寻求心理帮助或干预';
    }

    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 0,
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                Icons.bar_chart,
                color: Theme.of(context).primaryColor,
                size: 24,
              ),
              const SizedBox(width: 8),
              Text(
                '总分评估',
                style: Theme.of(context).textTheme.headlineMedium?.copyWith(
                  fontSize: 18,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          Text(
            '您的SCL-90评估结果（满分450分）：',
            style: Theme.of(
              context,
            ).textTheme.bodyMedium?.copyWith(color: Colors.grey.shade600),
          ),
          const SizedBox(height: 20),
          Text('总分：${totalScore.toInt()} 分'),
          Text('平均分：${averageScore.toStringAsFixed(2)} 分'),
          const SizedBox(height: 12),
          Text('心理状态解读：${getScoreLevel(totalScore)}'),
          Text('建议说明：${getScoreSuggestion(totalScore)}'),
        ],
      ),
    );
  }

  Widget _buildAnalysisReport(AppState appState) {
    final analysisResult = appState.analysisResult ?? '';

    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 0,
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                Icons.psychology,
                color: Theme.of(context).primaryColor,
                size: 24,
              ),
              const SizedBox(width: 8),
              Text(
                '详细分析报告',
                style: Theme.of(context).textTheme.headlineMedium?.copyWith(
                  fontSize: 18,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.grey.shade50,
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: Colors.grey.shade200),
            ),
            child: SelectableText(
              analysisResult,
              style: Theme.of(
                context,
              ).textTheme.bodyMedium?.copyWith(height: 1.6),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildActionButtons(AppState appState) {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 0,
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '分享和保存',
            style: Theme.of(context).textTheme.headlineMedium?.copyWith(
              fontSize: 18,
              fontWeight: FontWeight.w600,
            ),
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(
                child: ElevatedButton.icon(
                  onPressed: () {
                    _copyResultToClipboard(appState);
                  },
                  icon: const Icon(Icons.copy, size: 20),
                  label: const Text('复制结果'),
                  style: ElevatedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(vertical: 12),
                  ),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: OutlinedButton.icon(
                  onPressed: _isGeneratingLink
                      ? null
                      : () {
                          _generateShortLink(appState);
                        },
                  icon: _isGeneratingLink
                      ? const SizedBox(
                          width: 16,
                          height: 16,
                          child: CircularProgressIndicator(strokeWidth: 2),
                        )
                      : const Icon(Icons.link, size: 20),
                  label: Text(_isGeneratingLink ? '生成中...' : '生成链接'),
                  style: OutlinedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(vertical: 12),
                    side: BorderSide(color: Theme.of(context).primaryColor),
                  ),
                ),
              ),
            ],
          ),
          if (_shortLink != null) ...[
            const SizedBox(height: 16),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.green.shade50,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.green.shade200),
              ),
              child: Row(
                children: [
                  Icon(
                    Icons.check_circle,
                    color: Colors.green.shade600,
                    size: 20,
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: SelectableText(
                      _shortLink!,
                      style: TextStyle(
                        color: Colors.green.shade700,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                  IconButton(
                    onPressed: () {
                      Clipboard.setData(ClipboardData(text: _shortLink!));
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('链接已复制到剪贴板')),
                      );
                    },
                    icon: const Icon(Icons.copy, size: 16),
                  ),
                ],
              ),
            ),
          ],
          const SizedBox(height: 16),
          SizedBox(
            width: double.infinity,
            child: ElevatedButton.icon(
              onPressed: () {
                context.read<AppState>().reset();
                context.read<AppState>().setCurrentPage(0);
              },
              icon: const Icon(Icons.refresh, size: 20),
              label: const Text('重新测试'),
              style: ElevatedButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 12),
                backgroundColor: Colors.grey.shade600,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDisclaimer() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.amber.shade50,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: Colors.amber.shade200),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(Icons.warning_amber, color: Colors.amber.shade600, size: 24),
              const SizedBox(width: 8),
              Text(
                '免责声明',
                style: Theme.of(context).textTheme.headlineMedium?.copyWith(
                  fontSize: 18,
                  fontWeight: FontWeight.w600,
                  color: Colors.amber.shade700,
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Text(
            '• 本测试结果仅供参考，不能替代专业心理健康诊断\n'
            '• 如果您感到严重心理困扰，请及时寻求专业心理咨询师或医生的帮助\n'
            '• 心理健康状况可能会随时间变化，建议定期进行评估\n'
            '• 本测试基于您的自我报告，结果的准确性依赖于您的诚实回答',
            style: Theme.of(context).textTheme.bodyMedium?.copyWith(
              color: Colors.amber.shade700,
              height: 1.5,
            ),
          ),
          const SizedBox(height: 16),
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.red.shade50,
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: Colors.red.shade200),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '🚨 紧急情况联系方式',
                  style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                    fontWeight: FontWeight.w600,
                    color: Colors.red.shade700,
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  '如果您有自伤或自杀的想法，请立即联系：\n'
                  '• 全国心理危机干预热线：400-161-9995\n'
                  '• 北京心理危机研究与干预中心：010-82951332\n'
                  '• 上海心理援助热线：021-34289888',
                  style: Theme.of(context).textTheme.bodySmall?.copyWith(
                    color: Colors.red.shade700,
                    height: 1.5,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void _copyResultToClipboard(AppState appState) {
    final result = appState.analysisResult ?? '';
    Clipboard.setData(ClipboardData(text: result));
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: const Text('结果已复制到剪贴板'),
        backgroundColor: Theme.of(context).primaryColor,
      ),
    );
  }

  void _generateShortLink(AppState appState) async {
    setState(() {
      _isGeneratingLink = true;
    });

    try {
      final apiService = ApiService();
      final testId = appState.testId ?? 'unknown';
      final shortLink = await apiService.getResultShortLink(testId);

      setState(() {
        _shortLink = shortLink;
      });

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: const Text('链接生成成功'), backgroundColor: Colors.green),
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('生成链接失败：$e'), backgroundColor: Colors.red),
      );
    } finally {
      setState(() {
        _isGeneratingLink = false;
      });
    }
  }
}
